import {useHistory} from 'react-router-dom';
import React from 'react';
import PageHeader from '@/components/page-header';
import styles from './index.less';
import {Avatar, List} from 'antd';
import util from '@/utils';
import AMapLoader from '@amap/amap-jsapi-loader';
import 'weui';


const type = 7;

const queryArticlesByType = async () => {
   const {data} = await util.request({
      url: `/article/type/${type}`
   });
   return data;
};


const queryTreeAdoptions = async () => {
   const {data} = await util.request({
      url: `/tree-adoption`
   });
   return data;
};


const updateTreeAdoptions = async (data: any) => {
   const response = await util.request({
      url: `/tree-adoption/adoption`,
      method: 'POST',
      data: data
   });
   return response;
};

const ParkMapImageRatio = 0.6649;

const mapImageWidth = 767;


const registerMap = async (mapContainer: any) => {

   const AMap = await AMapLoader.load({
      key: '1dc3efb3ad13e905f009b865e8a82768',
      version: '2.0',
      plugins: [],
      AMapUI: {
         version: '1.1',
         plugins: ['overlay/SimpleMarker', 'control/BasicControl', 'overlay/SimpleInfoWindow']
      }
   });

   const map = new AMap.Map(mapContainer, {
      center: [mapImageWidth / 200 - 0.2, mapImageWidth * ParkMapImageRatio / 200 + 0.4],
      lang: 'zh_cn',
      zooms: [6, 8],
      features: [],
      zoom: 7,
      doubleClickZoom: false,
      layers: [
         new AMap.ImageLayer({
            bounds: new AMap.Bounds([0, 0], [mapImageWidth / 100, mapImageWidth * ParkMapImageRatio / 100]),
            url: `${util.ossUrl}/map/tree-map.png`
         })
      ],
      limitBounds: new AMap.Bounds([-0.3, -0.3], [mapImageWidth / 100 + 0.3, mapImageWidth * ParkMapImageRatio / 100 + 0.3])
   });
   const {AMapUI}: any = window;
   map.addControl(new AMapUI.BasicControl.Zoom({
      position: 'rb',
      showZoomNum: false,
      theme: 'dark'
   }));
   map.on('click', (e: any) => {
      console.log(e);
      map.clearInfoWindow();
   });
   return map;
};


export default function TreeAdoptionPage() {
   const history = useHistory();
   const articleListState = React.useState<Array<Article>>([]);
   const mapPointState = React.useState<Array<any>>([]);
   const modalOpenState = React.useState<boolean>(false);


   React.useEffect(() => {
      queryArticlesByType().then((data) => {
         articleListState[1](data);
      });
   }, [mapPointState[0]]);
   React.useEffect(() => {
      queryArticlesByType().then((data) => {
         articleListState[1](data);
      });
   }, []);

   const selectPointState = React.useState<number>(-1);
   const parkPointInfoRef = React.useRef<any>();

   const mapContainerRef = React.useRef<any>();

   React.useEffect(() => {
      registerMap(mapContainerRef.current).then(async map => {
         const {AMapUI, AMap}: any = window;
         const data = await queryTreeAdoptions();
         mapPointState[1](data);
         data.forEach((mark: { lng: any; lat: any; name: any; }, index: any) => {
            const marker = new AMapUI.SimpleMarker({
               topWhenClick: true,
               iconTheme: 'numv1',
               map: map,
               iconStyle: 'red',
               anchor: 'top-left',
               position: [mark.lng, mark.lat],
               label: {
                  content: `<div>${mark.name}</div>`,
                  direction: 'bottom'
               }
            });
            marker.on('click', (e: any) => {
               selectPointState[1](index);
               e.target.dom.classList.add(styles.parkMapMarkerAnimation);
               const infoWindow = new AMap.InfoWindow({
                  anchor: 'bottom-center',
                  content: parkPointInfoRef.current
               });
               infoWindow.open(map, [e.lnglat.lng, e.lnglat.lat]);
               setTimeout(() => {
                  e.target.dom.classList.remove(styles.parkMapMarkerAnimation);
               }, 1200);
            });
         });
      });
   }, []);

   return <div className={styles.layout}>
      <PageHeader
         onBack={() => history.goBack()}
         title='树木认养'
      />

      <div ref={mapContainerRef} className={styles.treeMap} />
      <List
         dataSource={articleListState[0]}
         renderItem={(item: any) => (
            <List.Item className={styles.item} onClick={() => {
               history.push({
                  pathname: `/article-page/${item.id}`
               });
            }}>
               <List.Item.Meta
                  avatar={<Avatar shape='square' size='large' src={item.thumb} />}
                  title={<b>{item.title}</b>}
                  description={<div className={styles.description}>
                     <span>{item.represent}</span>
                     <span>{item?.date && new Date(item?.date).toLocaleString()}</span>
                     <span>阅读:{item?.count}</span>
                  </div>}
               />
            </List.Item>
         )}
         itemLayout='horizontal'
         className={styles.treeAdoptionList}
      />
      <template>
         <div ref={parkPointInfoRef} className={styles.parkPointInfoWindow}>
            <img src={mapPointState[0][selectPointState[0]]?.img}
                 alt='' />
            <div>{mapPointState[0][selectPointState[0]]?.name}</div>
            <div className={styles.infoWindow}>
               <button className={styles.foot} onClick={async () => {
                  mapPointState[1](await queryTreeAdoptions());
                  modalOpenState[1](true);
               }}>
                  认养
               </button>
            </div>
         </div>
      </template>


      <div style={{display: modalOpenState[0] ? 'block' : 'none'}}>
         <div className='weui-mask' />
         <div className='weui-dialog'>
            <div className='weui-dialog__hd'><strong
               className='weui-dialog__title'>树木认养</strong>
            </div>
            <div
               className='weui-dialog__bd'>{mapPointState[0][selectPointState[0]]?.isMaster === 1 ?
               '当前树木已经被认养了哦' : '确定认养吗'}
            </div>
            <div className='weui-dialog__ft'>
               <a href='javascript:' id='dialog__btn_default'
                  className='weui-dialog__btn weui-dialog__btn_default' onClick={async () => {
                  modalOpenState[1](false);
                  mapPointState[1](await queryTreeAdoptions());
               }}>取消</a>

               {mapPointState[0][selectPointState[0]]?.isMaster === 0 &&
               <a href='javascript:' id='weui-dialog__btn_primary'
                  onClick={async () => {
                     modalOpenState[1](false);
                     await updateTreeAdoptions({
                        id: mapPointState[0][selectPointState[0]].id,
                        isMaster: 1,
                        master: localStorage.getItem('wxOpenId')
                     });
                     mapPointState[1](await queryTreeAdoptions());
                  }}
                  className='weui-dialog__btn weui-dialog__btn_primary'>确定</a>}
            </div>
         </div>
      </div>

   </div>;
}
